package love.xin.ui.diary

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import love.xin.R
import love.xin.adapter.EventAdapter
import love.xin.adapter.ImageAdapter
import love.xin.databinding.ActivityIncreaseBinding
import love.xin.view.CenteredGridLayoutManager
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class IncreaseActivity : AppCompatActivity() {
    private lateinit var bin: ActivityIncreaseBinding
    private val list = mutableListOf("")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        bin = ActivityIncreaseBinding.inflate(layoutInflater)
        setContentView(bin.root)
        initData()
        bin.choice.setOnClickListener {
            list.clear()
            pickImagesLauncher.launch("image/*")
        }

    }

    private fun initImage(list: MutableList<String>) {


       Log.d("size:", list.size.toString())
        bin.imgRcv.apply {
            adapter = ImageAdapter(this@IncreaseActivity,list)
            layoutManager = GridLayoutManager(this@IncreaseActivity, 3)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initData() {
        val adapter = EventAdapter(this@IncreaseActivity)
        val gridLayoutManager = GridLayoutManager(this, 5)

        gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                val totalItems = adapter.itemCount
                val itemsInLastRow = totalItems % 5

                return if (itemsInLastRow != 0 && position >= totalItems - itemsInLastRow) {
                    // 将跨度设置为5/itemsInLastRow，以确保最后一行的item居中
                    5 / itemsInLastRow
                } else {
                    1 // 正常情况下，跨度为1
                }
            }
        }

        bin.rcv.layoutManager = gridLayoutManager
        bin.rcv.adapter = adapter

        adapter.notifyDataSetChanged()
    }
    private val pickImagesLauncher = registerForActivityResult(ActivityResultContracts.GetMultipleContents()) { uris: List<Uri>? ->
        uris?.let {
            it.forEach { uri ->
                val file = copyFileToInternalStorage(uri)
                val absolutePath = file?.absolutePath
               list.add(absolutePath.toString())
            }
            initImage(list)
        }
    }
    private fun copyFileToInternalStorage(uri: Uri): File? {
        return try {
            val inputStream = contentResolver.openInputStream(uri)
            val file = File(filesDir, "copied_image_${System.currentTimeMillis()}.jpg") // 使用时间戳生成唯一文件名
            val outputStream = FileOutputStream(file)
            inputStream?.copyTo(outputStream)
            inputStream?.close()
            outputStream.close()
            file
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }
}